
import json
import logging
import random

from ihome_team3.libs.yuntongxun.ccp_sms import CCP

logger = logging.getLogger('django')

from django.http import HttpResponse, JsonResponse
from django.views import View

from django_redis import get_redis_connection

from ihome_team3.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import ccp_send_sms_code

class ImageCodeView(View):
    '''返回图形验证码的类视图'''

    def get(self, request):
        '''接收用户的uuid, 生成图形验证码返回'''
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')

        # 1.调用工具类 captcha 生成图形验证码
        text, image = captcha.generate_captcha()

        # 2.链接 redis, 获取链接对象
        redis_conn = get_redis_connection('verify_code')

        # 3.利用链接对象, 保存数据到 redis, 使用 setex 函数
        # redis_conn.setex('<key>', '<expire>', '<value>')
        redis_conn.setex('img_%s' % cur, 300, text)

        # 4.返回(图片)
        return HttpResponse(image,
                            content_type='image/jpg')


class SMSCodeView(View):
    def post(self, request):
        '''短信验证码'''
        dict = json.loads(request.body)
        mobile = dict.get('mobile')
        id = dict.get('id')
        text = dict.get('text')

        if not all([mobile, id, text]):
            return JsonResponse({'errno': '4004',
                                 'errmsg': '缺少参数'})

        redis_conn = get_redis_connection('verify_code')

        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'errno': '4001',
                                 'errmsg': '发送短信过于频繁'})

        image_code_server = redis_conn.get('img_%s' % id)

        if image_code_server is None:
            return JsonResponse({'errno': '4002',
                                 'errmsg': '图形验证码失效'})
        try:
            redis_conn.delete('img_%s' % id)
        except Exception as e:
            logger.error(e)

        image_code_server = image_code_server.decode()
        if image_code_server.lower() != text.lower():
            return JsonResponse({'errno': '4103',
                                 'errmsg': '验证码错误'})

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        pl = redis_conn.pipeline()

        pl.setex('sms_%s' % mobile, 300, sms_code)

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        pl.execute()

        # ccp_send_sms_code.delay(mobile, sms_code)

        return JsonResponse({'errno': '0',
                             'errmsg': '发送成功'})

